<template>
  <view class="safe-area-inset-bottom">
    <!-- 页头 -->
    <view class="agree_jn">
      <p class="care_p">
        1、为核验您的真实身份，励氪签将您的信息提交至公安部、电信运营商、银行等权威机构进行核验； <br/>
        2、您的信息仅用于实名认证及申请CA证书，未经您的许可，励氪签绝不会将您的信息用于其他用途； <br/>
        3、励氪签采用安全加密技术，确保您的个人信息安全，请您放心填写。<br/>
      </p>
      <!-- 表单填写 -->
      <uni-forms ref="ruleForm" :modelValue="ruleForm" :rules="rules" label-position="top" label-width="220rpx">
        <uni-forms-item label="认证方式" name="certifyType" :required="true">
          <uni-data-select v-model="ruleForm.certifyType" :localdata="typeArr" :clear="false"
                           @change="certificationType"/>
        </uni-forms-item>
        <view>
          <!-- 人脸识别-->
          <view class="careful_p" v-show="ruleForm.certifyType == 1">
            <span>1、仅支持中国大陆居民；</span>
            <span>2、您的身份信息及人脸信息将通过公安部身份信息系统进行核验，请确保身份证件是您本人的；</span>
          </view>
          <!-- 银行卡认证 -->
          <view class="careful_p" v-show="ruleForm.certifyType == 2 ">
            <span>1、支持中国大陆、港、澳、台及外籍人士；</span>
            <span>2、您的身份信息及银行卡信息将通过银行系统进行核验，请确保手机号为银行卡预留号码并可正常使用；</span>
          </view>
          <!-- 手机认证 -->
          <view class="careful_p" v-show="ruleForm.certifyType == 3 ">
            <span>1、仅支持中国大陆居民；</span>
            <span>2、您的身份信息及手机号码将通过电信运营商系统进行核验，请确保手机号为您本人实名的号码；</span>
          </view>
        </view>
        <!-- 姓名-->
        <uni-forms-item label="姓名" name="name" :required="true">
          <uni-easyinput v-model="ruleForm.name" type="text" placeholder="请输入您的姓名" :maxlength="25"/>
        </uni-forms-item>
        <!-- 证件类型-->
        <uni-forms-item label="证件类型" name="credentialType" :required="true" v-show="ruleForm.certifyType == 2">
          <uni-data-select
              placeholder="请选择证件类型"
              v-model="ruleForm.credentialType"
              :localdata="dicts.ec_person_certification_certificates_type"
              @change="setCropperDefaultImage"
              :clear="false"/>
        </uni-forms-item>
        <!-- 身份证号码-->
        <uni-forms-item label="身份证号码" name="idNumber" :required="true">
          <uni-easyinput
              v-model="ruleForm.idNumber"
              type="text"
              placeholder="请输入您的身份证号码"
              :clear="false"
              :maxlength="18"/>
        </uni-forms-item>
        <!-- 证件照片 上传/忘带-->
        <uni-forms-item label="证件照片" name="idNumberPic" :required="true">
          <template slot="label">
            <view>
              <span style="font-size: 28rpx;color: #dd524d;">*</span>
              <span style="font-size: 28rpx;color: #606266;">证件照片</span>
              <span @click="idcardNotice" class="themeColor" style="font-size:24rpx;margin-left: 15rpx;">查看证件拍摄要求</span>
            </view>
          </template>
          <uni-data-checkbox
              style="margin-top: 20rpx;"
              v-model="idPicRadio"
              :localdata="idPicArr"
              class="idpic-radio"
              @change="setIdPicRadioChange"
          />
          <view v-if="idPicRadio == 1" style="margin-top: 15px;display: flex;">
            <!-- 身份证正面图片上传 -->
            <view style="text-align:center;" @click="toIdCardCropper(0)">
              <img :src="idCardFrontImg" alt="" class="idcard-preview">
              <view style="color: #444;font-size: 20rpx;">正面图片</view>
            </view>
            <!-- 身份证反面图片上传 -->
            <view style="text-align:center;" @click="toIdCardCropper(1)">
              <img :src="idCardBackImg" style="margin-left: 15px" alt="" class="idcard-preview">
              <view style="color: #444;font-size: 20rpx;">反面图片</view>
            </view>
          </view>
        </uni-forms-item>
        <!-- 证件过期时间-->
        <uni-forms-item
            v-if="ruleForm.certifyType == 2 && ruleForm.credentialType != 1 && idPicRadio == 1"
            label="证件过期时间"
            name="credentialExpDate"
            :required="true">
          <view style="display: flex;align-items: center;">
            <uni-datetime-picker
                type="date"
                :clear-icon="false"
                style="margin-right: 5px;width: 100%;"
                v-model="ruleForm.credentialExpDate"
                :disabled="longTerm[0]"
            />
            <uni-data-checkbox multiple v-model="longTerm" :localdata="longTermArr"/>
          </view>
        </uni-forms-item>
        <!-- 银行卡号-->
        <uni-forms-item v-if="ruleForm.certifyType == 2" label="银行卡号" name="bankNumber" :required="true">
          <uni-easyinput v-model="ruleForm.bankNumber" type="text" placeholder="请输入本人银行卡号" :maxlength="20"/>
        </uni-forms-item>
        <!-- 实名手机号-->
        <uni-forms-item :label="(ruleForm.certifyType == 2)?'银行预留手机号':'实名手机号'" name="mobile" :required="true">
          <uni-easyinput
              v-model="ruleForm.mobile"
              type="text"
              :placeholder="ruleForm.certifyType == 2 ? '请输入开户时预留的手机号码' : '请输入实名手机号'"
              :disabled="true"/>
        </uni-forms-item>
        <!-- 验证码-->
        <uni-forms-item label="验证码" name="smsCode" :required="true">
          <view class="code">
            <uni-easyinput v-model="ruleForm.smsCode" type="text" placeholder="请输入短信验证码" :maxlength="6" :clearable="false"/>
			<span class="codeBtn" @click="getMobileCode">{{ counter }}</span>
          </view>
          <view class="sounds-text">收不到短信？使用语音验证码</view>
        </uni-forms-item>
      </uni-forms>
      <uni-data-checkbox
          v-if="ruleForm.certifyType == 1"
          style="margin: 20rpx 0;"
          v-model="agreeCollect"
          :localdata="agreeCollectArr"
          multiple/>
      <button class="shimingBtn" @click="submitForm" style="margin-top:0" v-if="ruleForm.certifyType == 1">立即认证</button>
      <button class="shimingBtn" @click="submitForm" v-else>确定提交</button>
    </view>

    <!-- 认证失败弹窗 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog type="warn" cancelText="取消" confirmText="重新认证" title="提示：" content="认证失败，请检查信息后，重新认证"/>
    </uni-popup>

    <!-- 证件认证拍摄要求 -->
    <uni-popup ref="idcardNoticetDialog" type="dialog" class="idpic-dialog">
      <uni-popup-dialog type="info" confirmText="知道了" title="证件拍摄要求" @confirm="dialogClose" @close="dialogClose">
        <template v-slot="content">
          <p style="font-size:24rpx;">证件拍摄时，请确保证件边框完整，<span style="color: red;">边框完整，字体清晰，亮度均匀。</span></p>
          <img src="@/static/images/id-card-notice.png" alt="" class="idcardNotice-pic" @click="preview">
        </template>
      </uni-popup-dialog>
    </uni-popup>
    <!-- 证件认证拍摄要求图片预览 -->
    <previewImage ref="previewImage" :imgs="idcardNoticePic" :saveBtn="false" :rotateBtn="false" :circular="false"/>
  </view>
</template>

<script>
import {getToken} from '@/utils/auth'
import previewImage from '@/components/previewImage/index';
import {getStaffCertification, personCer, personCerFaceBeforeCerPhone} from "@/api/ec/person/certification/info";
import {toGetSmsCode, updateSession} from "@/api/ec/person/user/userInfo";
import {goSignByMobile} from "../../../api/ec/person/certification/info";
import {changeUser, EncryptCommon} from "../../../api/login";
import {getDicts} from "../../../api/system/dict/data";
import config from '@/config'
import {getDictsForUni} from "../../../utils/dicts";
import {getCompany} from "../../../api/ec/work/company/company";
import {goSignPageOrIndexMiXin} from "../../../plugins/goSignPageOrIndexMiXin";

export default {
  components: {previewImage},
  mixins: [goSignPageOrIndexMiXin],
  data() {
    return {
      // 数据字典
      dicts: {
        // 证件类型字典
        ec_person_certification_certificates_type: [],
      },
      // 认证方式
      typeArr: [
        {value: 3, text: '手机号码认证（推荐）'},
        {value: 1, text: '人脸识别认证'},
        {value: 2, text: '银行卡认证'}
      ],
      // 证件照片选择
      idPicArr: [
        {text: '点击上传本人身份证件照片', value: 1},
        {text: '忘带证件，认证后补传', value: 2}
      ],
      // 长期有效
      longTermArr: [
        {text: '长期有效', value: true}
      ],
      // 人脸协议
      agreeCollectArr: [
        {text: '我同意励氪签采集人脸照片用于实名认证', value: true}
      ],
      // 证件认证拍摄要求图片
      idcardNoticePic: [require('@/static/images/id-card-notice.png')],
      // 用户信息
      userInfo: this.$store.getters.staffInfo,
      // 原始认证信息
      oldStaffCertInfo: {},
      // 证件是否长期有效
      longTerm: [],
      // 证件照片选择
      idPicRadio: 1,
      // 证件图片
      idCardFrontImg: undefined,
      idCardBackImg: undefined,
      // 人脸照片用于实名认证勾选框
      agreeCollect: [],
      // 表单数据
      ruleForm: {
        name: "",
        idNumber: "",
        mobile: "",
        smsCode: '',
        bankNumber: undefined,
        certifyType: 3,// 默认显示手机认证
        credentialType: 1,// 默认显示身份证
        idCardFrontImg: undefined,
        idCardBackImg: undefined,
        credentialExpDate: undefined,
      },
      // 表单验证
      rules: {
        name: {rules: [{required: true, errorMessage: "请输入姓名", trigger: "blur"},]},
        bankNumber: {
          rules: [
            {required: true, errorMessage: "请输入银行卡号", trigger: "blur"},
            {minLength: 15, maxLength: 19, errorMessage: "长度在 15 到 19 个字符", trigger: "blur"},
          ]
        },
        idNumber: {
          rules: [
            {required: true, errorMessage: "请输入身份证号码或证件号码", trigger: "blur"},
            // {minLength: 18, maxLength: 18, errorMessage: "长度必须是18位", trigger: "blur"},
            // {minLength: 18, maxLength: 18, errorMessage: "长度必须是18位", trigger: "change"},
          ]
        },
        smsCode: {
          rules: [
            {required: true, errorMessage: "请输入短信验证码", trigger: "blur"},
            {minLength: 6, maxLength: 6, errorMessage: "长度必须是6位", trigger: "blur"},
            {minLength: 6, maxLength: 6, errorMessage: "长度必须是6位", trigger: "change"},
          ]
        },
        certifyType: {rules: [{required: true, errorMessage: "请选择认证方式", trigger: "change"},]},
        credentialType: {rules: [{required: true, errorMessage: "请选择证件类型", trigger: "change"},]},
        mobile: {
          rules: [
            {required: true, errorMessage: "请输入手机号", trigger: "blur"},
            {minLength: 11, maxLength: 11, trigger: "change", errorMessage: "手机号长度必须是11位",},
            {minLength: 11, maxLength: 11, trigger: "blur", errorMessage: "手机号长度必须是11位",},
          ],
        }
      },
      // 短信验证码按钮获取加载中
      getSmsLoading: false,
      //短信验证码倒计时
      counter: "获取验证码",
    };
  },
  onLoad() {
    this.bindingRefreshData();
    this.getDicts()
    this.getStaffCertificationInfo()
    this.certificationType()
  },
  onUnload() {
    this.unbindingRefreshData();
  },
  methods: {
    /** 绑定 */
    bindingRefreshData() {
      // 证件图片剪切成功
      uni.$on('authenticationCropperSuccess', (base64, type) => {
        this.cropperSuccess(base64, type);
      });
    },
    /** 解除绑定 */
    unbindingRefreshData() {
      uni.$off('authenticationCropperSuccess');
    },
    // ===============================================================================================================
    // ==== 加载数据字典
    // ===============================================================================================================
    /**加载数据字典*/
    getDicts() {
      // 加载证件类型数据字典
      getDicts("ec_person_certification_certificates_type").then(response => {
        this.dicts.ec_person_certification_certificates_type = getDictsForUni(response.data);
      });
    },
    /** 认证方式选择改变 **/
    certificationType() {
      if (!!this.$refs['ruleForm']) {
        // 清除验证提示文字
        this.$refs['ruleForm'].clearValidate();
      }
      // 2022-09-09 沟通如下：三个认证方式的手机号码都不允许进行修改，默认显示用户注册的手机号码；
      this.ruleForm.mobile = this.userInfo.mobile
    },
    // ===============================================================================================================
    // ==== 加载页面数据
    // ===============================================================================================================
    /** 获取认证信息 */
    getStaffCertificationInfo() {
      uni.showLoading({title: '加载中...', mask: true});
      getStaffCertification().then(response => {
        uni.hideLoading()
        this.oldStaffCertInfo = response.data;
        if (null != this.oldStaffCertInfo) {
          // 证件图片
          this.oldStaffCertInfo.idCardFrontImg = (!!this.oldStaffCertInfo.idCardFrontImg) ? "data:image/png;base64," + this.oldStaffCertInfo.idCardFrontImg : null;
          this.oldStaffCertInfo.idCardBackImg = (!!this.oldStaffCertInfo.idCardBackImg) ? "data:image/png;base64," + this.oldStaffCertInfo.idCardBackImg : null;
          // 证件效期
          let credentialExpDate;
          if (this.oldStaffCertInfo.credentialExpDate == "长期") {
            this.longTerm = [true];
            credentialExpDate = undefined;
          } else {
            this.longTerm = [false];
            credentialExpDate = this.oldStaffCertInfo.credentialExpDate + "";
          }
          // 表单数据
          this.ruleForm = {
            name: this.oldStaffCertInfo.name,
            mobile: this.userInfo.mobile,
            idNumber: this.oldStaffCertInfo.idNumber,
            certifyType: this.oldStaffCertInfo.certifyType,
            credentialType: this.oldStaffCertInfo.credentialType,
            bankNumber: this.oldStaffCertInfo.bankNumber,
            credentialExpDate: credentialExpDate,
            smsCode: undefined,
          };
        }
        this.setCropperDefaultImage();
      }).catch(() => {
        uni.hideLoading()
      });
    },
    /** 设置证件默认图片 */
    setCropperDefaultImage() {
      // 正面图片
      if (this.oldStaffCertInfo == undefined || this.oldStaffCertInfo.idCardFrontImg == null || this.oldStaffCertInfo.idCardFrontImg == '') {
        this.idCardFrontImg = (this.certifyType == 2 && this.credentialType != 1) ? require("@/static/images/idcard-zheng.jpg") : require('@/static/images/card-people.jpg')
      } else {
        this.idCardFrontImg = this.oldStaffCertInfo.idCardFrontImg;
      }
      // 反面图片
      if (this.oldStaffCertInfo == undefined || this.oldStaffCertInfo.idCardBackImg == null || this.oldStaffCertInfo.idCardBackImg == '') {
        this.idCardBackImg = (this.certifyType == 2 && this.credentialType != 1) ? require('@/static/images/idcard-fan.jpg') : require('@/static/images/card-guo.jpg')
      } else {
        this.idCardBackImg = this.oldStaffCertInfo.idCardBackImg;
      }
    },
    // ===============================================================================================================
    // ==== 证件照片相关
    // ===============================================================================================================
    /** 图案比弹出框 */
    dialogClose() {
      this.$refs.idcardNoticetDialog.close()
    },
    /** 查看证件拍摄要求 */
    idcardNotice() {
      this.$refs.idcardNoticetDialog.open('center')
    },
    /** 预览图片证件拍摄要求图片 */
    preview() {
      this.$refs.previewImage.open(0)
    },
    /** 证件照片选择类型 */
    setIdPicRadioChange() {
      if (this.idPicRadio == 2) {
        this.idCardFrontImg = undefined;
        this.idCardBackImg = undefined;
        this.ruleForm.idCardFrontImg = undefined;
        this.ruleForm.idCardBackImg = undefined;
      } else {
        this.setCropperDefaultImage();
      }
    },
    /** 修改证件图片 */
    toIdCardCropper(idCartType) {
      let defaultImage;
      // 0 正面；1 反面
      if (idCartType == 0) {
        defaultImage = this.idCardFrontImg;
      } else {
        defaultImage = this.idCardBackImg;
      }
      let imageSrc
      // 组装图片加载地址
      if (defaultImage.startsWith("data:image/png;base64,")) {
        imageSrc = defaultImage;
      } else {
        imageSrc = config.baseUrl + "/common/lksign-authentication?path=" + defaultImage + "&token=" + getToken();
      }
      // 跳转页面
      uni.navigateTo({url: "/pages/common/imageCropper/index?callbackMethod=authenticationCropperSuccess&type=" + idCartType + "&imageSrc=" + encodeURIComponent(imageSrc)});
    },
    /** 身份证剪切成功回调方法 */
    cropperSuccess(base64, type) {
      if (type == 0) {
        this.idCardFrontImg = base64;
        this.ruleForm.idCardFrontImg = base64;
      } else {
        this.idCardBackImg = base64;
        this.ruleForm.idCardBackImg = base64;
      }
    },
    // ===============================================================================================================
    // ==== 短信验证码
    // ===============================================================================================================
    /** 获取手机验证码 **/
    getMobileCode() {
      let mobile = this.ruleForm.mobile;
      this.getSmsLoading = true;
      let smsType = 4;
      const param = {mobile, smsType};
      toGetSmsCode(param).then(response => {
        this.getSmsLoading = false;
        this.$modal.msgSuccess("短信验证码已发送到您手机，请注意查收");
        this.counter =this.$smsCounter;
        const timer = setInterval(() => {
          this.counter--;
          if (this.counter <= 0) {
            this.counter = "";
            clearInterval(timer);
          }
        }, 1000);
      })
    },
    // ===============================================================================================================
    // ==== 提交认证
    // ===============================================================================================================
    /** 提交按钮 */
    submitForm() {
      this.$refs.ruleForm.validate().then(res => {
        // 证件图片验证
        if ((this.ruleForm.idCardFrontImg != undefined && this.ruleForm.idCardFrontImg != '')
            && (this.ruleForm.idCardBackImg == undefined || this.ruleForm.idCardBackImg == '')) {
          this.$modal.msgError("请上传身份证反面图片！");
          return false;
        }
        if ((this.ruleForm.idCardFrontImg == undefined || this.ruleForm.idCardFrontImg == '')
            && (this.ruleForm.idCardBackImg != undefined && this.ruleForm.idCardBackImg != '')) {
          this.$modal.msgError("请上传身份证正面图片");
          return false;
        }
        // 证件过期时间
        if (this.longTerm[0]) {
          this.ruleForm.credentialExpDate = "长期";
        }
        // 提交认证
        if (this.ruleForm.certifyType != 1) {
          // 非人脸认证（银行卡认证或手机号认证）
          this.toPersonCer();
        } else {
          if (this.agreeCollect[0] != true) {
            this.$modal.msgError("请勾选协议")
            return false;
          } else {
            // 人脸认证
            this.toPersonFaceCer();
          }
        }
      });
    },
    /** 非人脸认证（银行卡认证或手机号认证） 立即认证 */
    toPersonCer() {
      uni.showLoading({title: '加载中...', mask: true});
      // 立即认证提交
      personCer(this.ruleForm).then(response => {
        // 认证完成完成刷新登录用户session信息
        updateSession().then(response => {
          uni.hideLoading()
          this.$store.dispatch('GetInfo').then((res) => {
            this.$modal.msgSuccess("认证成功");
            // 跳转到首页
            this.goSignPageOrIndex(response.data.mobile,1);
          })
        }).catch(() => {
          uni.hideLoading()
        });
      }).catch((error) => {
        uni.hideLoading()
        this.$refs.alertDialog.open('center')
      });
    },
    /** 人脸认证 : 提交认证 个人实名认证 (人脸识别前的手机号三网认证) */
    toPersonFaceCer() {
      if (this.oldStaffCertInfo != null && this.oldStaffCertInfo.name == this.ruleForm.name && this.oldStaffCertInfo.idNumber == this.ruleForm.idNumber
          && (this.ruleForm.idCardFrontImg == undefined || this.ruleForm.idCardFrontImg == '' || !this.ruleForm.idCardFrontImg.startsWith("data:image"))
          && (this.ruleForm.idCardBackImg == undefined || this.ruleForm.idCardBackImg == '' || !this.ruleForm.idCardBackImg.startsWith("data:image"))) {
        // 人脸识别前的手机号三网认证成功过，则直接显示二维码验证窗口
        this.toFaceCer();
        return false;
      }
      // 人脸识别前的手机号三网未认证成功过，则进行三网认证
      uni.showLoading({title: '加载中...', mask: true});
      personCerFaceBeforeCerPhone(this.ruleForm).then(response => {
        uni.hideLoading()
        // 开始二维码验证窗口
        this.toFaceCer();
      }).catch(() => {
        uni.hideLoading()
      });
    },
    /** 人脸认证 */
    async toFaceCer() {
      let param = {};
      param.mobile = this.$store.getters.staffInfo.mobile;
      param.name = this.ruleForm.name;
      param.idNumber = this.ruleForm.idNumber;
      param.staffId = this.$store.getters.staffInfo.id;
      // param.verifyCode = verifyCode;
      param.dirName = "personFace";
      console.log(param)
      let data;
      // 加密参数
      await EncryptCommon(new Buffer(JSON.stringify(param)).toString('base64')).then((response) => {
        data = response;
      });
      this.$tab.navigateTo(`/pages/authentication/personal/facePersonal?verifyType=0&data=${data}`)
    },
  },
};
</script>

<style lang="scss" scoped>
.sounds-text {
  text-align: right;
  margin-top: 6rpx;
  color: #777;
  font-size: 26rpx;
}

.idpic-dialog {
  ::v-deep .uni-dialog-content {
    display: block
  }
}

.idcardNotice-pic {
  width: 100%;
  margin-top: 10rpx;
}

::v-deep .uni-data-checklist .checklist-group {
  margin-top: 8rpx;
  justify-content: space-between !important;
  width: 90% !important;
}

.disform ::v-deep .uni-input-input {
  color: #666666;
}

::v-deep .uni-forms-item.is-direction-top .uni-forms-item__label {
  padding: 0;
  line-height: 0;
}

::v-deep .uni-forms-item__label {
  height: 50rpx;
}

::v-deep .uni-forms-item {
  margin-bottom: 22rpx;
}

page {
  background: $uni-bg-color;
  // position: relative;
  // overflow: hidden;
}

// 获取验证码
.code {
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: relative;

  .codeBtn {
    color: $uni-color-primary;
	position: absolute;
	right: 20rpx;
  }

}

// 认证btn
.shimingBtn {
  background-color: $uni-color-primary;
  color: #fff;
  font-size: 32rpx;
  margin: 60rpx 0;
}

.agree_jn {
  padding: 0 30rpx;
  position: relative;

  .careful_p {
    color: #666666;
    font-size: 24rpx;
    padding: 12rpx 16rpx;
    background-color: #fafbfd;
    border: solid 1rpx #e6e6e6;
    margin: 0 0 22rpx 0;

    p:first-child {
      font-size: 24rpx;
      color: #5c5a5a;
      margin: 0;
    }

    span {
      display: block;
    }
  }

  .care_p {
    color: #666666;
    text-align: left;
    font-size: 24rpx;
    border: 1rpx solid #f4ffff;
    padding: 12rpx;
    margin: 20rpx 0 10rpx 0;
    background-color: #f4ffff;
  }
}

.idcard-preview {
  position: relative;
  display: inline-block;
  width: 228rpx;
  height: 144rpx;
}

</style>
